#coding=utf-8
import datetime
today = datetime.date.today().isoformat()

import pygtk
pygtk.require('2.0')

import gtk, gobject
from stgui.guidb import *
from stgui.listview import get_listview
from stgui.tray import StTray
import sdsource.web.sina as sina

def is_between(a, b):
    if a < b * 1.02 and a > b * 0.98:
        return True
    
    return False   

def prepare_rpdata(rps):
    data = []
    for rp in rps:
        code = rp.code
        name = find_stock(code).name
        
        d = [code, name, rp.time, rp.now, rp.change, rp.open, rp.jump, rp.volume]

        data.append(d)
    return data
    
def update(win, lv, tray, group):
    global is_warnned
    
    #print 'updating...'
    codes = [s.code for s in group.stocks]
    rps = sina.get_rtprices(codes)
    
    #更新价格
    is_visibled = win.get_property('visible')
    if is_visibled:
        
        data = prepare_rpdata(rps)
        
        model = lv.get_model()       
        model.clear()
        
        for d in data:
            model.append(d)
    
    #预警
    for rp in rps:
        c = rp.code
        s = group.get_mystock(c)
        now = rp.now
        
        r = False
        for p in s.pps:
            if is_between(now, p.value):
                r = True
                break
                    
        if r and (not is_warnned[c]):
                
            is_warnned[c] = True
            msg = '%s(%s): %s 价格进入警戒区'%(s.name, s.code, now)
            tray.warnning(msg)
        
        elif (not r) and is_warnned[c]:
                 
            is_warnned[c] = False
            msg = '%s(%s): %s 价格离开警戒区'%(s.name, s.code, now)
            tray.warnning(msg)
                
    return True

def on_iconified(win, event):
    state = event.new_window_state
    if state == gtk.gdk.WINDOW_STATE_ICONIFIED:
        win.is_iconified = True
        win.hide()

cols = ['code', 'name', 'time', 'now', 'change', 'open', 'jump', 'volume']

sg1 = get_stgroups()[0]
codes = [s.code for s in sg1.stocks]

is_warnned ={}
for c in codes:
    is_warnned[c] = False
        
rps = sina.get_rtprices(codes)
data = prepare_rpdata(rps)
lv = get_listview(cols, data)

win = gtk.Window()

win.set_title("Eagle(鹰的眼睛) -- (%s)A股实时行情"%today)
win.set_icon_from_file('eagle.png')
win.set_border_width(5)
win.set_default_size(550, 200)
win.set_position(gtk.WIN_POS_CENTER_ALWAYS)
win.is_iconified = False

win.connect("destroy", gtk.main_quit)
win.connect("window-state-event", on_iconified)

tray = StTray(win)

timer = gobject.timeout_add (5000, update, win, lv, tray, sg1)

scr_win = gtk.ScrolledWindow()
scr_win.add(lv)

win.add(scr_win)
win.show_all()

gtk.main()
